﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Pipes;
using System.Linq;
using System.Text;

namespace BillHelper
{
    public class NamedPipeClientStreamTool
    {
        private const string PipeName = "SaoMiaoShiBie";
        private static Encoding encoding = Encoding.UTF8;

        public static void Write(string message)
        {
           // Console.WriteLine("发送 " + message);

            var _pipe = new NamedPipeClientStream
               (
                   ".",
                   PipeName,
                   PipeDirection.InOut,
                   PipeOptions.Asynchronous | PipeOptions.WriteThrough
               );
           
            _pipe.Connect();

            if (_pipe.IsConnected)
            {
                _pipe.ReadMode = PipeTransmissionMode.Message;

                byte[] data = encoding.GetBytes(message);

                _pipe.Write(data,0, data.Length);

                _pipe.Flush();
                _pipe.WaitForPipeDrain();

                data = new byte[65535];

                var count = _pipe.Read(data, 0, data.Length);

                if (count > 0)
                {
                    message = encoding.GetString(data, 0, count);

                    //Dispatcher.BeginInvoke(new Action(() => {
                    //    tblRecMsg.Text = message;
                    //}));
                    //Console.WriteLine("接收 " + message);
                }
            }

        }
    }
}
